package com.neuedu.aop.advice;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;


public class MyAdvice {

 
    public void beforeMethod(JoinPoint joinpoint){


        String info = String.format("%s  调用了%s方法",

                    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()),
                    joinpoint.getSignature().toString()
                );
        System.out.println(info);
    }


    /**
     *  后置通知  即使报错，也能执行
     *
     * @param joinpoint
     */
    public void afterMethod(JoinPoint joinpoint){
        System.out.println("【后置通知】 方法执行完成了");
    }


    /**
     *  返回通知  一旦报错，不会执行
     *
     * @param joinpoint
     */
    public void afterReturning(JoinPoint joinpoint,Object result){

        System.out.println("result = " + result);
        System.out.println("【afterReturning】 方法执行完成了");
    }


    /**
     * 异常通知
     * @param joinpoint
     * @param ex
     */
    public void afterThrowing(JoinPoint joinpoint,Exception ex){
        ex.printStackTrace();
        System.out.println("异常通知日志" + joinpoint.toString());
    }


    /**
     * 环绕通知
     * @param pjp
     * @return
     */
    public Object aroundMethod(ProceedingJoinPoint pjp) {
        Object obj = null;
        try{
            System.out.println("环绕通知日志" + pjp.toString()+"开启事务");

            //调用方法
            obj = pjp.proceed();
            System.out.println("环绕通知日志" + pjp.toString()+"提交事务");

        }catch(Throwable e){
            System.out.println("环绕通知日志" + pjp.toString()+"回滚事务");

            e.printStackTrace();
        }
        return obj;
    }





}